package com.wkq.service.impl;

import com.wkq.dao.IPermissionDao;
import com.wkq.dao.IRoleDao;
import com.wkq.dao.IUserDao;
import com.wkq.domain.Permission;
import com.wkq.domain.Role;
import com.wkq.domain.UserInfo;
import com.wkq.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class IUserServiceImpl implements IUserService {

    @Autowired
    private IUserDao iUserDao;
    @Autowired
    private IRoleDao iRoleDao;
    @Autowired
    private IPermissionDao iPermissionDao;
    //  注入该对象用来对密码进行加密操作
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public int addRoleToUser(String userId, List<String> roleId) {
        int flag = iUserDao.addRoleToUser(userId, roleId);
        return flag;
    }

    @Override
    public UserInfo findById(int id) {
        UserInfo userInfo = iUserDao.findById(id);
        List<Role> roleList = iRoleDao.findAllByUserId(userInfo.getId());
        for (Role role : roleList) {
            List<Permission> permissionList = iPermissionDao.findAllByRoleId(role.getId());
            role.setPermissions(permissionList);
        }
        userInfo.setRoles(roleList);
        return userInfo;
    }

    @Override
    public int save(UserInfo userInfo) {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        int flag = iUserDao.save(userInfo);
        return flag;
    }

    @Override
    public List<UserInfo> findAll() {
        return iUserDao.findAll();
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = iUserDao.findByUsername(username);
        List<Role> RoleList = iRoleDao.findAllByUserId(userInfo.getId());
//        User user = new User(userInfo.getUsername(), "{noop}" + userInfo.getPassword(), getAuthority(RoleList));
        User user = new User(userInfo.getUsername(), userInfo.getPassword(),
                userInfo.getStatus() == 0 ? false : true,
                true, true, true, getAuthority(RoleList));
        return user;
    }

    //    返回一个List集合，集合中装入的是角色描述
    private List<SimpleGrantedAuthority> getAuthority(List<Role> RoleList) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Role role : RoleList) {
            list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return list;
    }
}
